﻿using System;
using System.Text;

public class SendData 
{
	/// <summary>
	/// Aysn lock
	/// </summary>
	public readonly object AsynLock = new object();

	/// <summary>
	/// Method ID
	/// </summary>
	public short ID;

	/// <summary>
	/// The data be sended to server
	/// </summary>
	public string Content;

	/// <summary>
	/// The data being sended
	/// </summary>
	public byte[] SendBuf;

	/// <summary>
	/// Request Type
	/// </summary>
	public ReqType ReqType;

	/// <summary>
	/// The time when sending data
	/// </summary>
	public DateTime SendTime;

	/// <summary>
	/// Whether this data is sending now
	/// </summary>
	public bool IsSending = false;

	/// <summary>
	/// Whether Need Callback
	/// </summary>
	public bool NeedWait = false;

	/// <summary>
	/// Error Message
	/// </summary>
	public string ErrorMsg = null;

	/// <summary>
	/// To do sth after server return data successfully
	/// </summary>
	public Action<TcpState> Ondone = null;

	/// <summary>
	/// Length of SendBuf
	/// </summary>
	public int Length {
		get { return SendBuf.Length; }
	}

	public SendData(short method, string content,ReqType reqType = ReqType.None, Action<TcpState> ondone = null) {
		ID = method;
		Content = content;
		Ondone = ondone;
		ReqType = reqType;
		NeedWait = reqType.Equals(ReqType.NeedWait);

		SendTime = DateTime.Now;

		if (ReqType.Equals(ReqType.Callback)) {
			method = (short)(method | 1 << ConstantDef.headLength * 8 - 1);
		}

		byte[] temp1 = BitConverter.GetBytes(method);
		byte[] temp2 = Encoding.UTF8.GetBytes(Content);

		SendBuf = new byte[temp2.Length + ConstantDef.headLength];

		Buffer.BlockCopy(temp1, 0, SendBuf, 0, temp1.Length);
		Buffer.BlockCopy(temp2, 0, SendBuf, ConstantDef.headLength, temp2.Length);
	}
}

public class RecData
{
	/// <summary>
	/// Aysn lock
	/// </summary>
	public readonly object AsynLock = new object();

	/// <summary>
	/// Method ID
	/// </summary>
	public short ID;

	/// <summary>
	/// Request Type
	/// </summary>
	public ReqType ReqType;

	/// <summary>
	/// The data be sended to server
	/// </summary>
	public string Content;

	/// <summary>
	/// Error Message
	/// </summary>
	public string ErrorMsg = null;

	/// <summary>
	/// Request Result
	/// </summary>
	public TcpState ReqResult = TcpState.Success;

	public RecData(short method, string content, TcpState state)
	{
		ID = method;
		Content = content;
		ReqResult = state;
	}
}

public enum ReqType 
{
	None,

	/// <summary>
	/// 需要等待的请求
	/// </summary>
	NeedWait,

	/// <summary>
	/// 请求返回
	/// </summary>
	Callback,
}

public enum TcpState {
	None,
	Success,
	Error,
	TimeOut
}
